package pers.csw.lookBook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.csw.lookBook.mapper.BooksMapper;
import pers.csw.lookBook.dto.BookTagDto;
import pers.csw.lookBook.entity.BookLabel;
import pers.csw.lookBook.entity.Books;
import pers.csw.lookBook.entity.Category;
import pers.csw.lookBook.entity.Tag;
import pers.csw.lookBook.service.BookService;
import pers.csw.lookBook.service.CategoryService;
import pers.csw.lookBook.service.LabelService;
import pers.csw.lookBook.service.TagService;

import java.util.ArrayList;
import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BooksMapper, Books> implements BookService {
    @Autowired
    BooksMapper booksMapper;
    @Autowired
    LabelService labelService;
    @Autowired
    TagService tagService;
    @Autowired
    CategoryService categoryService;

    @Override
    public List<Books> getMan() {
        return booksMapper.getMan();
    }

    @Override
    public List<Books> getWoMan() {
        return booksMapper.getWoMan();
    }

    @Override
    public List<BookTagDto> getBookByCategoryId(Integer categoryId) {
        QueryWrapper<Books> booksQueryWrapper = new QueryWrapper<>();
        booksQueryWrapper.eq("category",categoryId);
        List<BookTagDto> bookTagDtoList = new ArrayList<>();
        booksMapper.selectList(booksQueryWrapper).forEach(books -> {
            bookTagDtoList.add(getBookTagDto(books));
        });
        return bookTagDtoList;
    }

    @Override
    public List<BookTagDto> searchBook(String title) {
        List<BookTagDto> bookTagDtoList = new ArrayList<>();
        booksMapper.searchBooks(title).forEach(books -> {
            bookTagDtoList.add(getBookTagDto(books));
        });
        return bookTagDtoList;
    }

    public BookTagDto getBookTagDto(Books books){
        BookTagDto tagDt = new BookTagDto();
        QueryWrapper<BookLabel> labelQueryWrapper =new QueryWrapper<>();
        labelQueryWrapper.eq("book_id",books.getId());
        List<Tag> tagList = new ArrayList<>();
        labelService.list(labelQueryWrapper).forEach(label->{
            Tag byId = tagService.getById(label.getTagId());
            tagList.add(byId);
        });
        Category byId = categoryService.getById(books.getCategory());
        tagDt.setCategoryName(byId.getTitle());
        tagDt.setTagList(tagList);
        tagDt.setBooks(books);
        return tagDt;
    }
}
